<?php

require_once 'Zend/Filter/Unix/Abstract.php';

class Zend_Filter_Unix_Head extends Zend_Filter_Unix_Abstract
{
    const UNIT_LINE = 'LINE';
    const UNIT_WORD = 'WORD';
    const UNIT_BYTE = 'BYTE';

    private $_count = null;

    private $_unit = null;

    public function __construct($count = 10, $unit = Zend_Filter_Unix_Head::UNIT_LINE)
    {
        $this->setCount($count);
        $this->setUnit($unit);
    }

    public function setCount($count)
    {
        $this->_count = $count;
    }

    public function getCount()
    {
        return $this->_count;
    }

    public function setUnit($unit)
    {
        $this->_unit = strtoupper($unit);
    }

    public function getUnit()
    {
        return $this->_unit;
    }

    public function filter($value)
    {
        switch($this->_unit) {
            case Zend_Filter_Unix_Head::UNIT_LINE:
                $lines = $this->_parseLines($value);
                $count = min($this->_count, count($lines));
                $lines = array_slice($lines, 0, $count);
                return implode('', $lines);

            case Zend_Filter_Unix_Head::UNIT_WORD:
                $words = $this->_parseWords($value);
                $count = 2 * $this->_count - 1;
                if(ctype_space($words[0])) {
                    $count++;
                }
                $count = min($count, count($words));
                $words = array_slice($words, 0, $count);
                return implode('', $words);

            case Zend_Filter_Unix_Head::UNIT_BYTE:
                $count = min($this->_count, strlen($value));
                return substr($value, 0, $count);
        }
    }
}